// 路由拦截
router.beforeEach((to, from, next) => {
	if (to.matched.some(record => { !record.meta.noCheckSession })) {
		let isLogin = auth.checkAuth() // 我们登录成功后会设置个字段(authenticated)为true.这里就是获取那个字段.

		if (!isLogin) {
			console.error('Place login!')
			next({
				path: '/login',
				query: { redirect: to.fullPath } // 跳转到登录页面
			})
		} else {
			next()
		}
	} else {
		next()
	}
})

// 拦截器
export const interceptor = function (Vue) {
	Vue.http.interceptor.push((request, next) => {
		let tokenVal = sessionStorage.getItem('token') // 取出token
		if (tokenVal) {
			request.headers['token'] = tokenVal // 存在的话,把Token放在请求头中
		}

		next((response) => {
			let status = response.status
			let data = response.data
			try {
				if (typeof data === 'string') {
					data = JSON.parse(data)
				}
			} catch (e) {

			}

			let isError = false
			let duration = 0
			let options = {
				message: ""
			}
			if (status === 401) {
				location.href = '/login' // 401未授权,重新登录
			} else if (status === 500) {
				isError = true
				options.message = response.statusText
				options.description = response.data
				Message.error(options) // 调用全局组件提示
				location.href = '/login'
			} else if (status === 200) {
				// custom error
				if (response.data['<isError>']) {
					// ...
				} 
				// timeout
				else if (data.data && data.data['ecode'] === '401') {
					// ...
				}
			}
		})
	})
}